package com.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.regex.Pattern;

/**
 * Created by mengdexuan on 2017/2/28 11:24.
 */
public class NetUtils {
	public static final String LOCALHOST = "127.0.0.1";
	public static final String ANYHOST = "0.0.0.0";
	private static final Pattern IP_PATTERN = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3,5}$");
	private static volatile InetAddress LOCAL_ADDRESS = null;

	private NetUtils() {
	}

	private static boolean isValidAddress(InetAddress address) {
		if(address != null && !address.isLoopbackAddress()) {
			String name = address.getHostAddress();
			return name != null && !"0.0.0.0".equals(name) && !"127.0.0.1".equals(name) && IP_PATTERN.matcher(name).matches();
		} else {
			return false;
		}
	}

	public static String getLocalHost() {
		InetAddress address = getLocalAddress();
		return address == null?"127.0.0.1":address.getHostAddress();
	}

	public static InetAddress getLocalAddress() {
		if(LOCAL_ADDRESS != null) {
			return LOCAL_ADDRESS;
		} else {
			InetAddress localAddress = getLocalAddress0();
			LOCAL_ADDRESS = localAddress;
			return localAddress;
		}
	}

	private static InetAddress getLocalAddress0() {
		InetAddress localAddress = null;

		try {
			localAddress = InetAddress.getLocalHost();
			if(isValidAddress(localAddress)) {
				return localAddress;
			}
		} catch (Exception var6) {
			var6.printStackTrace();
		}

		try {
			Enumeration e = NetworkInterface.getNetworkInterfaces();
			if(e != null) {
				while(e.hasMoreElements()) {
					try {
						NetworkInterface e1 = (NetworkInterface)e.nextElement();
						if(!e1.isLoopback() && !e1.isVirtual() && e1.isUp()) {
							Enumeration addresses = e1.getInetAddresses();

							while(addresses.hasMoreElements()) {
								try {
									InetAddress e2 = (InetAddress)addresses.nextElement();
									if(isValidAddress(e2)) {
										return e2;
									}
								} catch (Exception var5) {
									var5.printStackTrace();
								}
							}
						}
					} catch (Exception var7) {
						var7.printStackTrace();
					}
				}
			}
		} catch (Exception var8) {
			var8.printStackTrace();
		}

		System.err.println("Could not get local host ip address, will use 127.0.0.1 instead.");
		return localAddress;
	}
}
